package com.xmxsuperstar.app.client.twitter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.Properties;

import net.love5z.common.utils.StringUtils;
import net.love5z.common.utils.URLUtils;
import android.util.Log;

import com.xmxsuperstar.app.CommonConstants;
import com.xmxsuperstar.app.CommonConstants.HTTP_METHODS_ENUM;
import com.xmxsuperstar.app.client.ClientConstants;
import com.xmxsuperstar.app.client.tunnel.HttpTunnelClient;
import com.xmxsuperstar.app.client.twitter.oauth.OAuth;
import com.xmxsuperstar.http.HttpQueryParams;
import com.xmxsuperstar.http.HttpRequestMsg;
import com.xmxsuperstar.http.HttpResponseMsg;
import com.xmxsuperstar.http.TTURLUtils;

public class TwitterClient {

	private String tunnelServer = "";
	private int tunnelPort = 10001;
	private String accessToken;
	private String accessTokenSecret;
	private String consumerKey;
	private String consumerSecret;

	public static void main(String[] args) throws IOException {
		TwitterClient tc = new TwitterClient();
		Log.i(ClientConstants.LogTag,
				tc.get("http://api.twitter.com/1/statuses/retweeted_to_me.json?since_id=0&count=20"));

		// Map<String, String> params = new HashMap<String, String>();
		// params.put("status", "测试");
		// Log.i(ClientConstants.LogTag, tc.post(
		// "http://api.twitter.com/1/statuses/update.json", params));
	}

	public TwitterClient() {
		try {
			Properties tunnelProp = new Properties();

			tunnelProp.load(TwitterClient.class
					.getResourceAsStream("/tunnel.properties"));

			this.tunnelServer = tunnelProp.getProperty("tunnel.server");
			this.tunnelPort = Integer.valueOf(tunnelProp
					.getProperty("tunnel.port"));

			Properties twitterProp = new Properties();

			twitterProp.load(TwitterClient.class
					.getResourceAsStream("/twitter.properties"));

			this.accessToken = twitterProp.getProperty("oauth.accessToken");
			this.accessTokenSecret = twitterProp
					.getProperty("oauth.accessTokenSecret");
			this.consumerKey = twitterProp.getProperty("oauth.consumerKey");
			this.consumerSecret = twitterProp
					.getProperty("oauth.consumerSecret");
		} catch (IOException e) {
			Log.e(ClientConstants.LogTag, e.getMessage());
		}
	}

	public TwitterClient(String tunnelHost, int tunnelPort) {

		this.tunnelServer = tunnelHost;
		this.tunnelPort = tunnelPort;

	}

	protected String get(String urlString) {

		Log.i(ClientConstants.LogTag, urlString);

		URL url = null;
		try {
			url = new URL(urlString);
		} catch (MalformedURLException e) {
			Log.e(ClientConstants.LogTag, e.getMessage());
		}

		HttpTunnelClient htc = new HttpTunnelClient(tunnelServer, tunnelPort);
		OAuth oauth = new OAuth(accessToken, accessTokenSecret, consumerKey,
				consumerSecret);

		HttpRequestMsg reqMsg = new HttpRequestMsg();
		reqMsg.setMethod(HTTP_METHODS_ENUM.GET);
		reqMsg.setVersion(CommonConstants.HTTP_VERSION);
		reqMsg.setPath(URLUtils.getRequestPath(url));
		reqMsg.addHeader("Authorization", oauth.getAuthorizationHeaderContent(
				CommonConstants.HTTP_METHOD_NAMES.GET,
				URLUtils.getEndPoint(url), TTURLUtils.getQueryParams(url)));

		boolean isSecure = StringUtils.equalsIgnoreCase(
				CommonConstants.HTTP_PROTOCLS.HTTPS,
				URLUtils.getProtocolFromUrl(url));
		String host = URLUtils.getHostFromUrl(url);
		int port = URLUtils.getPortFromUrl(url);

		HttpResponseMsg resMsg = htc.request(host, port, isSecure, reqMsg);

		String res = resMsg.getBodyText();

		Log.i(ClientConstants.LogTag, res);

		return res;

	}

	public String post(String urlString, Map<String, String> params) {

		URL url = null;
		try {
			url = new URL(urlString);
		} catch (MalformedURLException e) {
			Log.e(ClientConstants.LogTag, e.getMessage());
		}

		HttpTunnelClient htc = new HttpTunnelClient(tunnelServer, tunnelPort);
		HttpRequestMsg reqMsg = new HttpRequestMsg();
		reqMsg.setMethod(HTTP_METHODS_ENUM.POST);
		reqMsg.setVersion(CommonConstants.HTTP_VERSION);
		reqMsg.setPath(URLUtils.getRequestPath(url));

		HttpQueryParams postParams = new HttpQueryParams();
		for (Map.Entry<String, String> entry : params.entrySet()) {
			postParams.add(URLUtils.urlEncode(entry.getKey()),
					URLUtils.urlEncode(entry.getValue()));
		}

		OAuth oauth = new OAuth(accessToken, accessTokenSecret, consumerKey,
				consumerSecret);
		HttpQueryParams queryParams = TTURLUtils.getQueryParams(url);
		queryParams.addAll(postParams);
		reqMsg.addHeader("Authorization", oauth.getAuthorizationHeaderContent(
				CommonConstants.HTTP_METHOD_NAMES.POST,
				URLUtils.getEndPoint(url), queryParams));

		// set body
		StringBuilder postContent = new StringBuilder();
		int i = 0;
		for (String key : postParams.getAllKeys()) {
			for (String value : postParams.get(key)) {
				String join = "&";
				if (i == 0) {
					join = "";
				}
				postContent.append(join).append(key + "=" + value);
				i++;
			}
		}
		byte[] bodyBytes = new byte[0];
		try {
			bodyBytes = postContent.toString().getBytes(
					CommonConstants.CHAR_ENCODING);
		} catch (UnsupportedEncodingException e) {
			Log.e(ClientConstants.LogTag, e.getMessage());
		}
		reqMsg.addHeader("Content-Length", String.valueOf(bodyBytes.length));
		reqMsg.addHeader("Content-type", "application/x-www-form-urlencoded");

		reqMsg.setBody(bodyBytes);

		boolean isSecure = StringUtils.equalsIgnoreCase(
				CommonConstants.HTTP_PROTOCLS.HTTPS,
				URLUtils.getProtocolFromUrl(url));
		String host = URLUtils.getHostFromUrl(url);
		int port = URLUtils.getPortFromUrl(url);

		HttpResponseMsg resMsg = htc.request(host, port, isSecure, reqMsg);

		String res = resMsg.getBodyText();

		Log.i(ClientConstants.LogTag, res);

		return res;

	}
}
